import {
  onLogin
} from "../api/miniProgramController";
import {
  mpId
} from "../utils/config";
import {
  getCustBaseByUserLoginState
} from "../api/custBaseController";
/**
 * 检查登录态是否过期。
 */
async function checkSession() {
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success() {
        return resolve(true)
      },
      fail() {
        return resolve(false)
      }
    })
  })
}

/**
 * 校验是否实名认证
 */
function checkRealName() {
  let name = wx.getStorageSync('userBase').name
  if (name) {
    return true
  }else{
    return false
  }
}

/**
 * 是否有custId
 */
function checkCustId() {
  const custId = wx.getStorageSync('custId')
  if (!custId) {
    getCustBaseByUserLoginState()
    .then(res => {
      if (res.success) {
        let userInfo = {
          "nickName": res.data.nickname,
          "gender": res.data.sex,
          "language": res.data.language,
          "city": res.data.city,
          "province": res.data.province,
          "country": res.data.country,
          "avatarUrl": res.data.headImgUrl,
          "vipType": res.data.vipType,
          "id": res.data.id
        }
        wx.setStorageSync('custId', res.data.id)
        wx.setStorageSync('userInfo', userInfo)
      }
    })
    return res.data.id?true:false
  }else{
    return false
  }
}

// 检测注册登录状态，返回 true / false
async function checkHasLogined() {
  const token = wx.getStorageSync('custId')
  if (!token) {
    return false
  }
  const loggined = await checkSession()
  console.log('检查登录态是否过期-----', loggined);
  if (!loggined) {
    const login = await login()
    return false
  }
  return true
}

async function login(page) {
  console.log('登录');
  let self = this
  wx.login({
    success: function (res) {
      console.log('login----', res);
      onLogin({
          code: res.code,
          mpId: mpId
        })
        .then(res => {
          console.log('-----------登录-----------');
          console.log(res);
          console.log('-----------登录-----------');
          wx.setStorageSync('userLoginState', res.data || '')
          getCustBaseByUserLoginState()
            .then(res => {
              if (res.success) {
                wx.setStorageSync('custId', res.data.id)
                let userInfo = {
                  "nickName": res.data.nickname,
                  "gender": res.data.sex,
                  "language": res.data.language,
                  "city": res.data.city,
                  "province": res.data.province,
                  "country": res.data.country,
                  "avatarUrl": res.data.headImgUrl,
                  "vipType": res.data.vipType,
                  "id": res.data.id
                }
                wx.setStorageSync('userInfo', userInfo)
                wx.setStorageSync('userBase', res.data)
              }
            })
        })
    }
  })
  if (page) {
    page.onShow()
  }
}

async function register(page) {
  let _this = this;
  wx.login({
    success: function (res) {
      let code = res.code;
      // 微信登录接口返回的 code 参数
      console.log('微信登录接口返回的 code 参数----', code);
    }
  })
}

async function checkAndAuthorize(scope) {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success(res) {
        if (!res.authSetting[scope]) {
          wx.authorize({
            scope: scope,
            success() {
              resolve() // 无返回参数
            },
            fail(e) {
              console.error(e)
              wx.showModal({
                title: '无权操作',
                content: '需要获得您的授权',
                showCancel: false,
                confirmText: '立即授权',
                confirmColor: '#e64340',
                success(res) {
                  wx.openSetting();
                },
                fail(e) {
                  console.error(e)
                  reject(e)
                },
              })
            }
          })
        } else {
          resolve() // 无返回参数
        }
      },
      fail(e) {
        console.error(e)
        reject(e)
      }
    })
  })
}

module.exports = {
  checkCustId: checkCustId,
  checkRealName: checkRealName,
  checkHasLogined: checkHasLogined,
  login: login,
  register: register,
  checkAndAuthorize: checkAndAuthorize
}